package com.ruoyi.system.service.impl.eleme;

import com.ruoyi.common.core.domain.entity.TaoBaoGoods;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.eleme.TaoBaoGoodsMapper;
import com.ruoyi.system.service.eleme.TaoBaoGoodsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.Buffer;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @ClassName TaoBaoServiceImpl
 * @Author 任宝坤
 * @Date 2025/9/11 15:36
 * @Version v1.0
 **/

@Service
public class TaoBaoServiceImpl implements TaoBaoGoodsService {

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Resource
    private TaoBaoGoodsMapper taoBaoGoodsMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUpdate(List<TaoBaoGoods> list) {
        // 获取所有的商品ID
        List<String> listIds = list.stream().map(TaoBaoGoods::getGoodId).collect(Collectors.toList());
        List<TaoBaoGoods> listGoods = taoBaoGoodsMapper.selectBatchIds(listIds);
        Map<String,TaoBaoGoods> exitMap = listGoods.stream().collect(Collectors.toMap(TaoBaoGoods::getGoodId, Function.identity()));
        List<TaoBaoGoods> insertList = new ArrayList<>();
        List<TaoBaoGoods> updateList  =new ArrayList<>();
        for (TaoBaoGoods goods : list) {
            if (exitMap.containsKey(goods.getGoodId())){
                goods.setId(exitMap.get(goods.getGoodId()).getId());
                updateList.add(goods);
            }else {
                insertList.add(goods);
            }
        }
        if (!insertList.isEmpty()){
            taoBaoGoodsMapper.insertBatch(insertList);
        }
        if (!updateList.isEmpty()){
            taoBaoGoodsMapper.updateBatchById(updateList);
        }
    }

    @Override
    public List<TaoBaoGoods> search(String goodName, String goodClass) {

        return taoBaoGoodsMapper.search(goodName, goodClass);
    }

    @Override
    public List<TaoBaoGoods> importFile(MultipartFile file) {
        try {
           // BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8));
            InputStreamReader inputStreamReader = new InputStreamReader(file.getInputStream());
            BufferedReader reader = new BufferedReader(inputStreamReader);

            CSVParser csvParser = new CSVParser(reader,CSVFormat.Builder.create(CSVFormat.DEFAULT)
                    .setHeader()
                    .setSkipHeaderRecord(true)
                    .setIgnoreHeaderCase(true)
                    .setTrim(true).build());

            /*CSVParser = CSVFormat.DEFAULT
                    .builder().setSkipHeaderRecord(true).build().parse(reader);
*/
            List<TaoBaoGoods> list = new ArrayList<>();
            for (CSVRecord record : csvParser) {
                TaoBaoGoods goods = new TaoBaoGoods();
                goods.setGoodId(record.get(0).trim());// 商品ID
                goods.setGoodName(record.get(1));
                goods.setGoodMainImg(record.get(2));
                goods.setShopName(record.get(4));
                goods.setGoodClass(record.get(5));
                goods.setDiscountPrice(record.get(7));
                goods.setFinaPrice(record.get(8));
                goods.setBrand(record.get(11));
                goods.setCouponDenomination(record.get(15));
                String dateStart = record.get(16).replaceAll("[^0-9-:]", " ").trim();
                if (StringUtils.isNotBlank(dateStart)){
                    goods.setCouponStart(LocalDateTime.parse(dateStart,formatter));
                }
                String dateEnd = record.get(17).replaceAll("[^0-9-:]", " ").trim();
                if (StringUtils.isNotBlank(dateEnd)){
                    goods.setCouponEnd(LocalDateTime.parse(dateEnd,formatter));
                }
                goods.setCouponShortLink(record.get(20));
                list.add(goods);
            }
            reader.close();
            csvParser.close();
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
